package net.tngou.crawler.drug;

import java.net.URL;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.tngou.c4j.Crawler;
import net.tngou.crawler.enums.StateEnum;
import net.tngou.crawler.pojo.Crawlerurl;
import net.tngou.crawler.pojo.Drug;
import net.tngou.crawler.pojo.POJO;
import net.tngou.crawler.util.DigestMD;
import net.tngou.crawler.util.StringUtil;



public interface CrawlerDrug {

	
	public void setId(long id) ;
	public List<URL> urls();
	public JSONObject getJson(URL url);
	public default void save(JSONObject json) {
		
		Drug drug = JSON.parseObject(json.toJSONString(), Drug.class);
		
		if(drug==null) return;
//		if(StringUtil.isEmpty(drug.getName()))return;
//		String md=DigestMD.MD5(drug.getUrl());
//		drug.setInstructions(json.getString("instructions"));
//		Crawlerurl crawlerurl = new Crawlerurl().get("md5='"+md+"'");
//		if(crawlerurl!=null)
//		{
//			crawlerurl.setState(StateEnum.上传完成.ordinal());
//			crawlerurl.update();
//		}
		POJO pojo = drug.get(new HashMap<String,Object>() {{
			put("onlinepharmacy", json.getLong("onlinepharmacy"));
			put("un", json.getString("un"));}});
		if(pojo==null)
		drug.save();
		
	};
	public default void run() {
		List<URL> urls = urls();
		for (URL e : urls) {
		
			JSONObject json = getJson(e);//第一次
			if(json!=null) {
				save(json);
			}else
			{
				json = getJson(e);//第二次
				if(json==null)json = getJson(e);//第三次
				if(json==null)json = getJson(e);//第四次
				if(json==null)json = getJson(e);//第五次
				if(json!=null) { 
					save(json);
				}
				else
				{				
					String md=DigestMD.MD5(e.toString());
					Crawlerurl crawlerurl = new Crawlerurl().get("md5='"+md+"'");
					if(crawlerurl!=null)
					{
						crawlerurl.setState(StateEnum.爬取失败.ordinal());
						crawlerurl.update();
					}
				}
			}
			
		};
		
		
	}
}
